package com.example.wai;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.*;
import com.baidu.platform.comapi.basestruct.GeoPoint;

/**
 * 定位练习Activity
 * Created by jale on 14-3-3.
 */
public class WhereAmI extends Activity {

    private final static String TAG = "com.example.wai.WhereAmI";
    private final static String KEY = "ao9SVPREDfEQDZBSFbutaGvR";

    BMapManager bMapManager = null;
    MapView mapView = null;
    //设置启用内置的缩放控件
    MapController mMapController = null;

    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            updateWithNewLocation(bdLocation);
        }

        @Override
        public void onReceivePoi(BDLocation bdLocation) {
            updateWithNewLocation(bdLocation);
        }
    };

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bMapManager = new BMapManager(getApplication());
        bMapManager.init(KEY, null);
        setContentView(R.layout.main);
        //注意：请在试用setContentView前初始化BMapManager对象，否则会报错
        mapView = (MapView) findViewById(R.id.bmapsView);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);
        //设置启用内置的缩放控件
        mMapController = mapView.getController();
        mMapController.setZoom(12.5f);//设置地图zoom级别
//        mapView.getController().enableClick(true);

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);//设置定位模式
        option.setCoorType("bd09ll");//返回的定位结果是百度经纬度，默认值gcj02
        option.setScanSpan(5000);//设置发起定位请求的间隔时间为5000ms
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setNeedDeviceDirect(true);//返回的定位结果包含手机机头的方向
        mLocationClient.setLocOption(option);
//        mLocationClient.setAccessKey(KEY);
        mLocationClient.registerLocationListener(myListener);    //注册监听函数
//        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//        Criteria criteria = new Criteria();
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);
//        criteria.setPowerRequirement(Criteria.POWER_LOW);
//        criteria.setAltitudeRequired(false);
//        criteria.setBearingRequired(false);
//        criteria.setSpeedRequired(false);
//        criteria.setCostAllowed(true);
//        String provider = locationManager.getBestProvider(criteria, true);
//
//        Location l = locationManager.getLastKnownLocation(provider);
//        updateWithNewLocation(l);
//
//        locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);
          mLocationClient.start();
          mLocationClient.requestLocation();
    }

//    private final LocationListener locationListener = new LocationListener() {
//        @Override
//        public void onLocationChanged(Location location) {
//            updateWithNewLocation(location);
//        }
//
//        @Override
//        public void onStatusChanged(String provider, int status, Bundle extras) {
//
//        }
//
//        @Override
//        public void onProviderEnabled(String provider) {
//
//        }
//
//        @Override
//        public void onProviderDisabled(String provider) {
//
//        }
//    };

    private void updateWithNewLocation(BDLocation l) {
        TextView myLocationText = (TextView) findViewById(R.id.myLocationText);
        String latLongStr = "No location found";
        String addressStr = "No address found";
        if (l != null) {
            double lat = l.getLatitude();
            double lng = l.getLongitude();
            latLongStr = "Lat:" + lat + "\n" + "Long:" + lng;

            double latitude = l.getLatitude();
            double longtitude = l.getLongitude();
//            Geocoder gc = new Geocoder(this, Locale.getDefault());
//            try {
//                List<Address> addressList = gc.getFromLocation(latitude, longtitude, 1);
//                StringBuilder sb = new StringBuilder();
//                if (addressList.size() > 0) {
//                    Address address = addressList.get(0);
//                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
//                        sb.append(address.getAddressLine(i)).append("\n");
//                    }
//                    sb.append(address.getLocality()).append("\n")
//                            .append(address.getPostalCode()).append("\n")
//                            .append(address.getCountryName());
//                    addressStr = sb.toString();
//                }
//            } catch (IOException e) {
//                Log.e(TAG, e.getMessage(), e);
//            } catch (Exception e) {
//                Log.e(TAG, e.getMessage(), e);
//            }
             addressStr = l.getAddrStr();

            // 得到mapView的控制权,可以用它控制和驱动平移和缩放
            GeoPoint point = new GeoPoint((int) (latitude * 1E6), (int) (longtitude * 1E6));
            //用给定的经纬度构造一个GeoPoint，单位是微度 (度 * 1E6)
            mMapController.setCenter(point);//设置地图中心点

            drawCircle(latitude, longtitude);
        }
        myLocationText.setText("Your Current Position is:\n" + latLongStr + "\n\n" + addressStr);
    }

    /**
     * 绘制圆，该圆随地图状态变化
     *
     * @return 圆对象
     */
    public Graphic drawCircle(double mLat, double mLon) {
        int lat = (int) (mLat * 1E6);
        int lon = (int) (mLon * 1E6);
        GeoPoint pt1 = new GeoPoint(lat, lon);

        //构建圆
        Geometry circleGeometry = new Geometry();

        //设置圆中心点坐标和半径
        circleGeometry.setCircle(pt1, 2500);
        //设置样式
        Symbol circleSymbol = new Symbol();
        Symbol.Color circleColor = circleSymbol.new Color();
        circleColor.red = 0;
        circleColor.green = 255;
        circleColor.blue = 0;
        circleColor.alpha = 126;
        circleSymbol.setSurface(circleColor, 1, 3, new Symbol.Stroke(3, circleSymbol.new Color(0xFFFF0000)));
        //生成Graphic对象
        return new Graphic(circleGeometry, circleSymbol);
    }


    @Override
    protected void onDestroy() {
        mapView.destroy();
        if (bMapManager != null) {
            bMapManager.destroy();
            bMapManager = null;
        }
        if(mLocationClient != null) {
            mLocationClient.stop();
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        mapView.onPause();
        if (bMapManager != null) {
            bMapManager.stop();
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        mapView.onResume();
        if (bMapManager != null) {
            bMapManager.start();
        }
        super.onResume();
    }

}